<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"vchao.top","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="记录一次排序犯的bug，说到底还是考虑不全……  问题现象今天突然发现项目中的一个列表排序出现了错乱，顿时很慌张，原来测试过的啊，没问题的呀，这是怎么回事，赶紧定位问题，现象如下：1-9条数据排序正常，10条以后数据排序也对。但是这两块顺序不对。正常应该先展示10条以后的数据，最后再展示1-9条数据。（后来得知，这个现象属于偶然~~和数据有关系） 列表中部分有序，但是整体排序不对…… 分析恩？这">
<meta property="og:type" content="article">
<meta property="og:title" content="纳尼？Collections对时间戳排序出错了？？">
<meta property="og:url" content="http://vchao.top/2021/08/25/%E7%BA%B3%E5%B0%BC%EF%BC%9FCollections%E5%AF%B9%E6%97%B6%E9%97%B4%E6%88%B3%E6%8E%92%E5%BA%8F%E5%87%BA%E9%94%99%E4%BA%86%EF%BC%9F%EF%BC%9F/index.html">
<meta property="og:site_name" content="乘风破浪">
<meta property="og:description" content="记录一次排序犯的bug，说到底还是考虑不全……  问题现象今天突然发现项目中的一个列表排序出现了错乱，顿时很慌张，原来测试过的啊，没问题的呀，这是怎么回事，赶紧定位问题，现象如下：1-9条数据排序正常，10条以后数据排序也对。但是这两块顺序不对。正常应该先展示10条以后的数据，最后再展示1-9条数据。（后来得知，这个现象属于偶然~~和数据有关系） 列表中部分有序，但是整体排序不对…… 分析恩？这">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-25T14:42:51.246Z">
<meta property="article:modified_time" content="2021-08-25T14:37:20.814Z">
<meta property="article:author" content="vchao">
<meta property="article:tag" content="bug">
<meta property="article:tag" content="排序">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://vchao.top/2021/08/25/%E7%BA%B3%E5%B0%BC%EF%BC%9FCollections%E5%AF%B9%E6%97%B6%E9%97%B4%E6%88%B3%E6%8E%92%E5%BA%8F%E5%87%BA%E9%94%99%E4%BA%86%EF%BC%9F%EF%BC%9F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>纳尼？Collections对时间戳排序出错了？？ | 乘风破浪</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">乘风破浪</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://vchao.top/2021/08/25/%E7%BA%B3%E5%B0%BC%EF%BC%9FCollections%E5%AF%B9%E6%97%B6%E9%97%B4%E6%88%B3%E6%8E%92%E5%BA%8F%E5%87%BA%E9%94%99%E4%BA%86%EF%BC%9F%EF%BC%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="vchao">
      <meta itemprop="description" content="怀揣好奇，梦想改变世界的菜鸟极客">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乘风破浪">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          纳尼？Collections对时间戳排序出错了？？
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-25 22:42:51 / 修改时间：22:37:20" itemprop="dateCreated datePublished" datetime="2021-08-25T22:42:51+08:00">2021-08-25</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index"><span itemprop="name">Android</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>记录一次排序犯的bug，说到底还是考虑不全……</p>
</blockquote>
<h1 id="问题现象"><a href="#问题现象" class="headerlink" title="问题现象"></a>问题现象</h1><p>今天突然发现项目中的一个列表排序出现了错乱，顿时很慌张，原来测试过的啊，没问题的呀，这是怎么回事，赶紧定位问题，现象如下：<br>1-9条数据排序正常，10条以后数据排序也对。但是这两块顺序不对。正常应该先展示10条以后的数据，最后再展示1-9条数据。（后来得知，这个现象属于偶然~~和数据有关系）</p>
<p>列表中部分有序，但是整体排序不对……</p>
<h1 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h1><p>恩？这是怎么回事？<br>列表采用的分页加载，莫非是 <strong>分页请求</strong> 数据的原因？</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">￥@#&amp;……*……@￥</span><br></pre></td></tr></table></figure>
<p>一顿分析后，得出结论，分页请求没问题，不是这个原因。</p>
<p>列表用的是RecycleView，莫非是 常见的 <strong>列表复用</strong> 的原因？</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">￥@#&amp;……*……@￥</span><br></pre></td></tr></table></figure>

<p>一顿分析后，得出结论，不是没问题。</p>
<p>那会不会是排序本身的问题呢？ </p>
<h2 id="那看一下排序的代码"><a href="#那看一下排序的代码" class="headerlink" title="那看一下排序的代码"></a>那看一下排序的代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 网络请求获取数据，封装再beanList中</span></span><br><span class="line">...</span><br><span class="line"><span class="comment">// 对beanList进行排序</span></span><br><span class="line">Collections.sort(beanList, <span class="keyword">new</span> Comparator&lt;Bean&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Bean bean1, Bean bean2)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//        降序写法</span></span><br><span class="line">        <span class="keyword">return</span> (<span class="keyword">int</span>) (bean2.getBuyTime() - bean1.getBuyTime());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>其实大佬一眼就能看出来原因了，奈何我这心大，看了好几遍，还总觉得没问题。<br>就这么几行代码咋能出错呢？还纠结了半天，最后才聚焦到了 int类型 上面……<br>是不是这个数值超过了int的最大值，所以计算错误了呢？</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">int的取值范围为： -2^31——2^31-1，即</span><br><span class="line">-21 4748 3648——21 4748 3647</span><br><span class="line"></span><br><span class="line">2147483647毫秒 ---&gt; 2147483 秒 ---&gt; 35791 分钟 ---&gt; 596 小时 </span><br><span class="line">≈ 25天</span><br><span class="line">2147483647秒 ---&gt; 35791406 分钟 ---&gt; 596523小时</span><br><span class="line">≈ 24855天 ≈ 68年</span><br></pre></td></tr></table></figure>
<p>也就是说，如果是毫秒作为单位的话，<strong>int类型最多表示25天时间。<br>如果时间超过这个范围，那么就会数据错误！</strong><br>如果是秒作为单位的话，int类型大约可以表示68年时间。<br>我这里之所以出错，是因为时间超过了这个范围，所以导致排序的时候，错误地判断了大小关系。</p>
<h1 id="解决问题"><a href="#解决问题" class="headerlink" title="解决问题"></a>解决问题</h1><p>至此，定位原因。解决方法也就简单了：<br>（尴尬，犯了基础的错误……）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Collections.sort(beanList, <span class="keyword">new</span> Comparator&lt;Bean&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Bean bean1, Bean bean2)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//        降序写法</span></span><br><span class="line">		<span class="comment">// 原先采用的多次比较的方法，先判断是否是同年月，再return时间差，费时费力。</span></span><br><span class="line">		<span class="comment">// 感谢评论区大佬 【常威追打来福】 指点，比较方法已经修改如下：</span></span><br><span class="line">		<span class="keyword">if</span>(bean2.getBuyTime() - bean1.getBuyTime() &gt; <span class="number">0</span>)&#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">		&#125;<span class="keyword">else</span> <span class="keyword">if</span>(bean2.getBuyTime() - bean1.getBuyTime() &lt; <span class="number">0</span>)&#123;</span><br><span class="line">			<span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">		&#125;<span class="keyword">else</span> &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">		&#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>程序开发是个细致的活，一定要细心呀！不要因为马虎，在基础的知识上面翻了车。<br>在此，再次回顾下基础类型的基础知识，切记勿再犯相关错误！</p>
<h1 id="扩展"><a href="#扩展" class="headerlink" title="扩展"></a>扩展</h1><p>在JAVA中一共有八种基本数据类型，他们分别是<br>byte、short、int、long、float、double、char、boolean </p>
<p>byte的取值范围为-128<del>127，占用1个字节（-2的7次方到2的7次方-1）<br>short的取值范围为-32768</del>32767，占用2个字节（-2的15次方到2的15次方-1）<br>int的取值范围为（-2147483648<del>2147483647），占用4个字节（-2的31次方到2的31次方-1）<br>long的取值范围为（-9223372036854774808</del>9223372036854774807），占用8个字节（-2的63次方到2的63次方-1）</p>
<p>float 3.402823e+38 ~ 1.401298e-45（e+38表示是乘以10的38次方，同样，e-45表示乘以10的负45次方）占用4个字节<br>double 1.797693e+308~ 4.9000000e-324 占用8个字节 </p>
<blockquote>
<p>float和double是表示浮点型的数据类型，他们之间的区别在于他们的精确度不同<br>double型比float型存储范围更大，精度更高，所以通常的浮点型的数据在不声明的情况下都是double型的，如果要表示一个数据是float型的，可以在数据后面加上“F”。<br>浮点型的数据是不能完全精确的，所以有的时候在计算的时候可能会在小数点最后几位出现浮动，这是正常的。 </p>
</blockquote>
<p>boolean型（布尔型）<br>这个类型只有两个值，true和false（真和非真） </p>
<p>char型（文本型）<br>用于存放字符的数据类型，占用2个字节</p>
<blockquote>
<p>采用unicode编码，它的前128字节编码与ASCII兼容，字符的存储范围在\u0000~\uFFFF</p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/bug/" rel="tag"># bug</a>
              <a href="/tags/%E6%8E%92%E5%BA%8F/" rel="tag"># 排序</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/08/25/%E6%9F%A5%E7%9C%8BAndroid%E8%AE%BE%E5%A4%87%E7%9A%84CPU%E6%9E%B6%E6%9E%84%E4%BF%A1%E6%81%AF/" rel="prev" title="查看Android设备的CPU架构信息">
      <i class="fa fa-chevron-left"></i> 查看Android设备的CPU架构信息
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/08/25/%E7%BB%99APP%E4%B8%8A%E4%BB%BD%E4%BF%9D%E9%99%A9%EF%BC%9A%E5%AE%89%E5%8D%93%E7%9A%84%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E6%8D%95%E8%8E%B7/" rel="next" title="给APP上份保险：安卓的全局异常捕获">
      给APP上份保险：安卓的全局异常捕获 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E7%8E%B0%E8%B1%A1"><span class="nav-number">1.</span> <span class="nav-text">问题现象</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%88%86%E6%9E%90"><span class="nav-number">2.</span> <span class="nav-text">分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%82%A3%E7%9C%8B%E4%B8%80%E4%B8%8B%E6%8E%92%E5%BA%8F%E7%9A%84%E4%BB%A3%E7%A0%81"><span class="nav-number">2.1.</span> <span class="nav-text">那看一下排序的代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3%E9%97%AE%E9%A2%98"><span class="nav-number">3.</span> <span class="nav-text">解决问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%89%A9%E5%B1%95"><span class="nav-number">5.</span> <span class="nav-text">扩展</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">vchao</p>
  <div class="site-description" itemprop="description">怀揣好奇，梦想改变世界的菜鸟极客</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">46</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备 17022751号-1 </a>
      <img src="https://beian.miit.gov.cn" style="display: inline-block;">
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vchao</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
